package com.leaf.u_spring.chapter01;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 * 样板式代码(boilerplate code)
 * 模拟JDBC操作
 * 
 */
public class BoilerplateCode {
	
	DataSource dataSource = null;
	
	String sql = "select id, firstname, lastname, salary from employee where id=?";

	//改造前
	public Employee getEmployeeById(long id){
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		
		try {
			conn = dataSource.getConnection();
			//查找员工
			stmt = conn.prepareStatement(sql);
			
			rs = stmt.executeQuery();
			Employee employee = null;
			if(rs.next()){
				//根据数据创建对象
				employee = new Employee();
				employee.setId(rs.getLong("id"));
				employee.setFirstName(rs.getString("firstname"));
				employee.setLastName(rs.getString("lastname"));
				employee.setSalary(rs.getBigDecimal("salary"));
			}
			return employee;
		} catch (SQLException e) {
			// 扑捉异常，也做不了太多事
		} finally {
			if(rs != null){
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
			if(stmt != null){
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return null;
	}
	
	private JdbcTemplate jdbcTemplate;
	//改造后
	//模板能够让你的代码关注于自身的职责
	public Employee getEmployeeById_1(long id){
		//SQL查询
		return jdbcTemplate.queryForObject(sql, new RowMapper<Employee>(){
			//将结果匹配为对象
			@Override
			public Employee mapRow(ResultSet rs, int rowNum) throws SQLException {
				Employee employee = new Employee();
				employee.setId(rs.getLong("id"));
				employee.setFirstName(rs.getString("firstname"));
				employee.setLastName(rs.getString("lastname"));
				employee.setSalary(rs.getBigDecimal("salary"));
				return employee;
			}
			//指定查询参数
		}, id);
	}
}

class Employee {
	
	private Long id;
	private String firstName;
	private String lastName;
	private BigDecimal salary;
	
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public BigDecimal getSalary() {
		return salary;
	}
	public void setSalary(BigDecimal salary) {
		this.salary = salary;
	}
	
}
